<template>
  <div>
    <el-page-header @back="goBack" content="语音转文字"/>
    <div class="bank"></div>
    <el-card header="语音转文字">
      <el-card>
        <el-input :readonly="true" id="word" v-model="word"></el-input>
      </el-card>
      <el-card>
        <el-button type="primary" @click="startRecognition">
          <span v-if="isListening">语音识别中...</span>
          <span v-else>语音识别</span>
        </el-button>
      </el-card>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "WordToAudio",
  data() {
    return {
      word: "",
      isListening: false,
      recognition: null
    }
  },
  mounted() {
    // 初始化 SpeechRecognition
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (SpeechRecognition) {
      this.recognition = new SpeechRecognition();
      this.recognition.lang = 'zh-CN';
      this.recognition.interimResults = false;
      this.recognition.maxAlternatives = 1;

      // 监听识别结果
      this.recognition.onresult = (event) => {
        const transcript = event.results[0][0].transcript;
        this.word = transcript;
        this.isListening = false;
      };

      // 监听识别结束
      this.recognition.onend = () => {
        this.isListening = false;
      };

      // 监听识别错误
      this.recognition.onerror = (event) => {
        console.error(event.error);
        this.isListening = false;
      };
    } else {
      this.$message.error("当前浏览器不支持语音识别功能");
    }
  },
  methods: {
    startRecognition() {
      if (!this.recognition) {
        this.$message.error("语音识别未初始化");
        return;
      }
      if (this.isListening) {
        this.$message("语音识别正在进行中...");
        return;
      }
      this.isListening = true;
      this.recognition.start();
    },
    goBack() {
      // this.$router.push({ path: "/entry" })
    }
  }
}
</script>

<style>
.bank {
  padding: 10px;
}
</style>
